/*
 @description: 定时群发
 @require: vue.js,client-api
 @date: 2015/11/25
 @author: Nero(Nero@Nero-zou.com)
 */
var SERVER_BASE=window.opener.SITE_URL+'/';
var accounts=window.opener.wxb.accounts;
var LoginWXB=window.opener.LoginWXB;
var Util=window.opener.Util;
var WechatFetch=window.opener.WechatFetch;
const defaultMaterialList={
    item:[],
    file_cnt: {
        total: 0,
        img_cnt: 0,
        voice_cnt: 0,
        video_cnt: 0,
        app_msg_cnt: 0,
        commondity_msg_cnt: 0,
        video_msg_cnt: 0,
        short_video_cnt: 0,
        app_msg_sent_cnt: 0
    }
};
var accountsInKey={};
for (var i = 0; i < accounts.length; i++) {
    var obj = accounts[i];
    accountsInKey[obj.wxid]=obj;
}

var utils = {
    showLoading: function (target) {
        var oldHtml = target.html();
        target.addClass('js-loading disabled');
        var fa = target.find('i.fa');
        if (fa.length == 0) {
            try {
                target.prepend('<i class="fa fa-spinner fa-loading"></i> ');
            } catch (e) {

            }
        } else {
            fa.attr('class', 'fa fa-spinner fa-loading');
        }
        return {
            revert: function () {
                target.html(oldHtml);
                target.removeClass('js-loading disabled');
            }
        };
    }
};

Vue.filter('wx_name', function (raw_id) {
    var account=accountsInKey[raw_id];
    if(!account){
        return raw_id;
    }
    return account.nickName;
});
Vue.filter('wx_id', function (raw_id) {
    var account=accountsInKey[raw_id];
    if(!account){
        return raw_id;
    }
    return account.userName;
});
Vue.filter('toDate', function (timeStamp) {
    try{
        return Util.dateParse(timeStamp*1000).fullRet.substr(0,16);
    }catch (e){

    }
    return timeStamp;
});

Vue.filter('statusText', function (status) {
    var types={
        '-1':'群发失败',
        '0':'等待群发',
        '1':'群发成功'
    };
    if(types[status]){
        return types[status];
    }
    return status;
});

var sendTimerList = new Vue({
    el: '#SendTimer',
    data: {
        showEdit:false,//是否显示 修改设置 界面
        editItem:{
            agree:true,
            mobile:'',
            send_time:'',
            send_date:'',
            send_hour:'',
            send_minute:'',
            news_id:"",
            title1:"",
            total_count:"",
            raw_id:"",
        },//当前正在 修改设置 的数据
        showSelectMaterial:false,//是否显示 更换素材 界面
        nowSelectMaterial:{app_id:0},//更换素材 - 当前选中的素材的数据
        loadingMaterialList:false,
        materialListParam:{
            currentPage:1,
            currentPageGo:1,
            totalPage:1,
            perPage:12
        },//更换素材 - 素材列表 参数
        list_material_heights:{
            col1:1,//第一列的高度 递增是为了 方便计算高度， 同高度时 优先放到 第一列
            col2:2,//第二列的高度
            col3:3//第三列的高度
        },
        materialData:defaultMaterialList,//更换素材 时的素材列表数据
        accounts:accounts,
        accountsInKey:accountsInKey,
        list: [],// 数据列表
        param:{
            status:"",
            nickName:"",
            raw_id:"",
        },
        loading:false,//是否 正在加载
        pager:{
            current: 1,
            total: 1
        }
    },
    methods: {
        search:function(){
            this.pager.current=1;
            if(this.param.nickName!=""){
                for (var i = 0; i < accounts.length; i++) {
                    var obj1 = accounts[i];
                    if(obj1.nickName==this.param.nickName){
                        this.param.raw_id=obj1.wxid;
                        break;
                    }
                }
                if(this.param.raw_id==""){
                    this.param.nickName="";
                }
            }else{
                this.param.raw_id="";
            }
            this.loadData();
        },
        loadData:function(data,isAppend){
            var _this=this;
            _this.loading=true;
            data=data?data:{};
            data.page=_this.pager.current;
            data.status=_this.param.status;
            data.raw_id=_this.param.raw_id;
            LoginWXB.getSendTimer(data).then(function (response) {
                _this.loading=false;
                if(isAppend){
                    _this.list=_this.list.concat(response.data);
                }else{
                    _this.list=response.data;
                }
                _this.pager.total= parseInt(response.totalCount/10);
            }).catch(function (err) {
                _this.loading=false;

                console.log(err);
            });
        },

        loadMore:function(){
            this.pager.current=this.pager.current+1;
            this.loadData({},true);
        },

        edit:function(item){
            if(accountsInKey[item.raw_id]==undefined){
                toastr.error("还未在客户端添加该公众号，该公众号登录邮箱为："+item.username,"无法修改设置");
                return;
            }
            var fullRet=Util.dateParse(item.send_time*1000).fullRet;
            item.send_date=fullRet.substr(0,10);
            item.send_hour=fullRet.substr(11,2);
            item.send_minute=fullRet.substr(14,2);
            item.agree=true;
            this.editItem=item;
            this.showEdit=true;
        },
        chooseMaterial:function(){
            //更换素材
            this.nowSelectMaterial.app_id=this.editItem.news_id;
            this.showSelectMaterial=true;
            this.materialListParam.currentPage=1;
            this.materialListParam.totalPage=1;
            this.materialData=defaultMaterialList;
            this.loadMaterialList();
        },
        updateSet: function () {
            var _this=this;
            var itemInfo=_this.editItem;
            var send_date=$('#send_date').val();//因为用了date-picker 日期变了之后，未修改 editItem.send_date
            var send_hour=itemInfo.send_hour;
            var send_minute=itemInfo.send_minute;
            var sendTime=new Date(send_date+' '+send_hour+':'+send_minute);
            var mobile=itemInfo.mobile;
            var agree=itemInfo.agree;

            var accountInfo=accountsInKey[itemInfo.raw_id];

            if(sendTime=='Invalid Date' || sendTime.getTime()<Date.now()+5*60*1000){
                toastr.error("","群发时间不对！");
                return false;
            }
            if(Util.isMobile(mobile)==false){
                toastr.error("","手机号码不对！");
                return false;
            }
            if(!agree){
                toastr.error("","请同意群发协议及群发规则！");
                $('.edit-container .rule-wrap').slideDown();
                return false;
            }

            var sendTimerConfig;
            try{
                sendTimerConfig=JSON.parse(localStorage.getItem("sendTimerConfig"));
            }catch(e){

            }
            if(!sendTimerConfig){
                sendTimerConfig={agree:false,mobile:''};
            }
            sendTimerConfig.agree=agree;
            sendTimerConfig.mobile=mobile;
            localStorage.setItem('sendTimerConfig',JSON.stringify(sendTimerConfig));

            itemInfo.send_time= parseInt(sendTime.getTime()/1000);

            LoginWXB.updateSendTimer({
                id:itemInfo.id,
                title1:itemInfo.title1,
                total_count:itemInfo.total_count,
                raw_id: itemInfo.raw_id,
                wx_name: accountInfo.nickName,
                wx_id: accountInfo.userName,
                username: accountInfo.account,
                password: itemInfo.password,
                mobile: itemInfo.mobile,
                send_time: send_date+' '+send_hour+':'+send_minute,
                news_id: itemInfo.news_id
            }).then(function () {
                toastr.success("","修改成功");
                _this.showEdit=false;
                _this.updateItem(itemInfo.id,itemInfo);
                loading.revert();
            }).catch(function (err) {
                toastr.error(err,"修改失败");
                _this.showEdit=false;
                loading.revert();
            });
            var loading=utils.showLoading($('._modal_sure_btn'));
        },
        cancel:function(item){
            //取消 定时群发
            var _this=this;
            var confirm=Win.confirm({
                content:'是否取消这个定时群发？',
                yesFunc:function(){
                    var btn=confirm.find('._model-sure-btn');
                    var loading=utils.showLoading(btn);
                    LoginWXB.deleteSendTimer(item.id).then(function () {
                        toastr.success("","取消定时群发成功");
                        loading.revert();
                        _this.deleteItem(item.id);
                        confirm.modal('hide');
                    }).catch(function (err) {
                        confirm.modal('hide');
                        toastr.error(err,"取消定时群发失败");
                    });
                    return false;
                }
            });
        },
        deleteItem:function(id){
            //取消成功后 删除那条记录
            for (var i = 0; i < this.list.length; i++) {
                var obj1 = this.list[i];
                if(obj1.id==id){
                    this.list.splice(i,1);
                    return;
                }
            }
        },
        updateItem:function(id,newData){
            //修改设置成功后  更新那条数据
            for (var i = 0; i < this.list.length; i++) {
                var obj1 = this.list[i];
                if(obj1.id==id){
                    for (var key in newData) {
                        obj1[key]=newData[key];
                    }
                    break;
                }
            }
            sendTimerList.$set('list',this.list);
        },
        getMinHeightCol:function(){
            //获取最矮的列 - 因为 布局用了三列，
            var max=Infinity;
            var result='';
            for (var col in this.list_material_heights) {
                if(this.list_material_heights[col]<max){
                    max=this.list_material_heights[col];
                    result=col;
                }
            }
            return result;
        },
        loadMaterialList: function () {
            //加载 选择素材 列表
            var _this=this;
            var accountObj=accountsInKey[_this.editItem.raw_id];

            _this.loadingMaterialList=true;
            var currentPage=_this.materialListParam.currentPage;
            var pageSize=_this.materialListParam.perPage;
            var start=currentPage?pageSize*(currentPage-1):0;
            if(start<0){
                start=0;
            }
            WechatFetch.getMaterialList(accountObj, start, pageSize).then(function (data) {
                _this.materialData=data;
                _render();
            }).catch(function (err) {
                _this.materialData=defaultMaterialList;

                if (err) {
                    toastr.error(err,"加载微信素材失败");
                    console.log(err);
                }
                _render();
            });

            function _render(){
                _this.loadingMaterialList=false;
                _this.list_material_heights.col1=1;
                _this.list_material_heights.col2=2;
                _this.list_material_heights.col3=3;
                _this.materialListParam.totalPage= Math.ceil( _this.materialData.file_cnt.app_msg_cnt/_this.materialListParam.perPage);
                var tempData=[];
                for (var i = 0, max = _this.materialData.item.length; i < max; i++) {
                    var data_i = _this.materialData.item[i];
                    var this_height=170+78*data_i.multi_item.length;
                    var col=_this.getMinHeightCol();
                    data_i.col=col;
                    data_i.height=this_height;
                    data_i.loading=false;
                    _this.list_material_heights[col]+=this_height;
                    if(data_i.app_id==_this.nowSelectMaterial.app_id){
                        _this.nowSelectMaterial=data_i;
                    }
                    tempData.push(data_i);
                }
                _this.materialData.item=tempData;
            }

        },
        materialListGoPrev:function(){
            this.materialListParam.currentPage--;
            this.loadMaterialList();
        },
        materialListGoNext:function(){
            this.materialListParam.currentPage++;
            this.loadMaterialList();
        },
        materialListGo:function(){
            if(this.materialListParam.currentPageGo>=this.materialListParam.totalPage){
                toastr.error("","不能超过最大页数");
                return;
            }
            this.materialListParam.currentPage=this.materialListParam.currentPageGo;
            this.loadMaterialList();
        },
        changeNowSelect:function(material_item){
            this.nowSelectMaterial=material_item;
        },
        updateCheckedMaterial:function(){
            this.editItem.news_id=this.nowSelectMaterial.app_id;
            this.editItem.title1=this.nowSelectMaterial.title;
            this.editItem.total_count=this.nowSelectMaterial.multi_item.length;
            this.showSelectMaterial=false;
        }

    }
});

function init() {
    $('.datepicker').datepicker({
        format: 'yyyy-mm-dd',
        startDate: '-0d',
        autoclose:true

    });
    $('#SendTimer').on('click','.form-header',function(){
        $(this).next('.rule-wrap').slideToggle();
    });
    sendTimerList.loadData();
}